package com.oilsoft.scm.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("jgnuplotserv")
public class ManagerJGNUPlotImpl implements ManagerJGNUPlot {

	@Override
	@Transactional
	public byte[] setConoturMap(File matrix) throws IOException {
		JGNUPlot jgnuPlot = new JGNUPlot();
		jgnuPlot.cmd("set contour both");
		jgnuPlot.cmd("set view 0,0");
		jgnuPlot.cmd("set pm3d");
		jgnuPlot.cmd("set cntrparam levels incremental 1,.5,5");
		jgnuPlot.cmd("set term svg enhanced font 'arial,8' size 500,500");
		jgnuPlot.cmd("splot '".concat(matrix.getAbsolutePath()).concat(
				"' matrix w linesp"));
		File f = File.createTempFile(matrix.getName(), ".svg");
		BufferedWriter writer = new BufferedWriter(new FileWriter(f));
		String noEmptyLine = null;
		while (!jgnuPlot.getStdInput().ready()
				&& !jgnuPlot.getStdError().ready()) {
		}
		do {
			noEmptyLine = jgnuPlot.getNoEmptyLine();
			if (noEmptyLine != null) {
				noEmptyLine += "\n";
				writer.write(noEmptyLine);
			}
		} while (noEmptyLine != null);
		// finalize the file svg
		writer.write("</svg>");
		writer.close();
		// destroy procces
		jgnuPlot.getP().destroy();
		// read bytes to svg
		FileInputStream stream = new FileInputStream(f);
		byte[] b = new byte[(int) f.length()];
		stream.read(b);
		stream.close();
		return b;
	}
}
